/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ins.web;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.Collections3;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.ins.entity.InsData;
import com.thinkgem.jeesite.modules.ins.entity.InsDataLink;
import com.thinkgem.jeesite.modules.ins.entity.InsField;
import com.thinkgem.jeesite.modules.ins.entity.InsTable;
import com.thinkgem.jeesite.modules.ins.service.InsDataLinkService;
import com.thinkgem.jeesite.modules.ins.service.InsDataService;
import com.thinkgem.jeesite.modules.ins.service.InsFieldService;
import com.thinkgem.jeesite.modules.ins.service.InsTableService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 检验报告书-数据Controller
 * @author fanqinglong
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/ins/insData")
public class InsDataController extends BaseController {

	@Autowired
	private InsTableService insTableService;
	@Autowired
	private InsDataService insDataService;
	@Autowired
	private InsDataLinkService insDataLinkService;
	@Autowired
	private InsFieldService insFieldService;
	@ModelAttribute
	public InsData get(@RequestParam(required=false) String id) {
		InsData entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = insDataService.get(id);
		}
		if (entity == null){
			entity = new InsData();
		}
		return entity;
	}
	
	@RequiresPermissions("ins:insData:view")
	@RequestMapping(value = {"list", ""})
	public String list(InsTable insTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (!SecurityUtils.getSubject().isPermitted("ins:insTable:viewAll")) {
			insTable.getSqlMap().put("dsf", InsTableService.getDSF(UserUtils.getUser().getId(), "1"));
		}
		Page<InsTable> page = insTableService.findPage(new Page<InsTable>(request, response), insTable); 
		model.addAttribute("page", page);
		model.addAttribute("insTable", insTable);
		return "modules/ins/insDataTableList";
	}
	@RequiresPermissions("ins:insData:view")
	@RequestMapping(value = {"view"})
	public String view(InsTable insTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (!SecurityUtils.getSubject().isPermitted("ins:insTable:viewAll")) {
			insTable.getSqlMap().put("dsf", InsTableService.getDSF(UserUtils.getUser().getId(), "128"));
		}
		Page<InsTable> page = insTableService.findPage(new Page<InsTable>(request, response), insTable); 
		model.addAttribute("page", page);
		model.addAttribute("insTable", insTable);
		return "modules/ins/insDataView";
	}
	@RequiresPermissions("ins:insData:view")
	@RequestMapping(value = {"importTableList"})
	public String importTableList(InsTable insTable, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (!SecurityUtils.getSubject().isPermitted("ins:insTable:viewAll")) {
			insTable.getSqlMap().put("dsf", InsTableService.getDSF(UserUtils.getUser().getId(), "32"));
		}
		Page<InsTable> page = insTableService.findPage(new Page<InsTable>(request, response), insTable); 
		model.addAttribute("page", page);
		model.addAttribute("insTable", insTable);
		return "modules/ins/insImportTableList";
	}
	
	@RequiresPermissions("ins:insData:view")
	@RequestMapping(value = {"dataList"})
	public String dataList(InsData insData, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<InsData> page = insDataService.findPage(new Page<InsData>(request, response), insData); 
		if (null != insData.getTable().getId()){
			InsTable table = insTableService.get(insData.getTable().getId());
			insData.setTable(table);
		}
		model.addAttribute("page", page);
		model.addAttribute("insData", insData);
		// 查询出该表所有的日期字段
		InsField insField = new InsField();
		insField.setTable(insData.getTable());
		List<InsField> fields = insFieldService.findDateList(insField);
		model.addAttribute("fields", fields);
		return "modules/ins/insDataList";
	}
	
	
	@RequiresPermissions("ins:insData:export")
	@RequestMapping(value = {"print"})
	@ResponseBody
	public String print(InsData insData,HttpServletRequest request,HttpServletResponse response){
		String url = "";
		if ("pdf".equals(Global.getConfig("printFormat"))) {
			url = insDataService.exportPDF(insData, request);
		}else{
			url = insDataService.export(insData, request);
		}
		if (url.indexOf("error:")>-1) {
			return url;
		}
		File file = new File(url);
		return FileUtils.downFile(file, request, response);
	}
	@RequiresPermissions("ins:insData:export")
	@RequestMapping(value = {"printPDF"})
	public String printPDF(InsData insData,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes){
		String result = insDataService.printPDF(insData, request);
		addMessage(redirectAttributes, result);
		redirectAttributes.addAttribute("table.id", insData.getTable().getId());
		return "redirect:" + adminPath + "/ins/insData/dataList?repage";
	}
	
	@SuppressWarnings("unchecked")
	@RequiresPermissions("ins:insData:export")
	@RequestMapping(value = {"exportList"})
	public String exportList(InsData insData,HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes){
		if (StringUtils.isBlank(insData.getTable().getId())) {
			addMessage(redirectAttributes, "参数错误！");
			return "redirect:" + adminPath + "/ins/insData/view?repage";
		}
		// 如果传过来的pagination参数是true，则为导出当前页面数据,否则为导出所有数据
		// true为分页，false为导出全部
		boolean flag = "true".equals(request.getParameter("pagination"));
		Page<InsData> page = new Page<>(request, response);
		List<List<String>> dataList = insDataService.findList(insData, page, flag);
		InsTable table = insTableService.get(insData.getTable().getId());
		String fileName = table.getName()+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		try {
			new ExportExcel(table.getName(), Collections3.extractToList(table.getInsFieldList(), "name")).setDataListIndiv(dataList).write(response, fileName).dispose();
			return null;
		} catch (IOException e) {
			addMessage(redirectAttributes, "导出数据失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/ins/insData/view?repage";
	}
	
	@RequiresPermissions("ins:insData:view")
	@RequestMapping(value = "fill")
	public String fill(InsData insData, Model model) {
		if (StringUtils.isEmpty(insData.getId()) && null != insData.getTable().getId()) {
			InsTable table = insTableService.get(insData.getTable().getId());
			insData.setTable(table);
			if (null != table.getInsFieldList()) {
				List<InsDataLink> dataLinks = insData.getDatas();
				for (int i = 0; i < table.getInsFieldList().size(); i++) {
					InsField field = table.getInsFieldList().get(i);
					if ("1".equals(field.getPreInput())) {
						String[] values = field.getPreValues().split(";+|；+");
						field.setInsValueList(Arrays.asList(values));
					}
					InsDataLink dataLink = new InsDataLink();
					dataLink.setField(field);
					dataLink.setTable(table);
					dataLinks.add(dataLink);
				}
				insData.setDatas(dataLinks);
			}
		}
		model.addAttribute("insData", insData);
		return "modules/ins/insDataFill";
	}
	
	@RequiresPermissions("ins:insData:edit")
	@RequestMapping(value = "toImport")
	public String toImport(InsData insData, Model model){
		model.addAttribute("insData", insData);
		return "modules/ins/insDataImport";
	}

	@RequiresPermissions("ins:insData:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(InsData insData, Model model, RedirectAttributes redirectAttributes) {
		String result = "success";
		if (!beanValidator(model, insData)){
			return fill(insData, model);
		}
		try {
			result = insDataService.saveData(insData);
		} catch (Exception e) {
			e.printStackTrace();
			result = "表内计算失败！请仔细检查数据及公式！";
		}
		return result;
	}
	
	
	@RequiresPermissions("ins:insData:edit")
	@RequestMapping(value = "unique")
	@ResponseBody
	public String unique(HttpServletRequest request){
		String pre = request.getParameter("pre");
		String value = request.getParameter(pre+".value");
		String id = request.getParameter("id");
		String fieldId = request.getParameter("fieldId");
		InsDataLink param = new InsDataLink();
		param.setField(new InsField(fieldId));
		param.setValue(value);
		List<InsDataLink> results = insDataLinkService.getForUnique(param);
		if (null != results && results.size() > 0) {
			for (int i = 0; i < results.size(); i++) {
				InsDataLink insDataLink = results.get(i);
				if (insDataLink.getData().getId().equals(id)) {
					results.remove(insDataLink);
				}
			}
			if (results.size() > 0) {
				return "false";
			}
		}
		return "true";
	}
	
	@RequiresPermissions("ins:insData:edit")
    @RequestMapping(value = "importFile", method=RequestMethod.POST)
	@ResponseBody
	public String importFile(InsData insData,MultipartFile file, RedirectAttributes redirectAttributes){
		String result = "";
		try {
			ImportExcel ei = new ImportExcel(file, 0, 0);
			result = insDataService.importFile(ei, insData);
		} catch (Exception e) {
			result = "error:导入失败！"+e.getMessage();
		}
		return result;
	}
	
	@RequiresPermissions("ins:insData:edit")
	@RequestMapping(value = "refresh", method=RequestMethod.POST)
	@ResponseBody
	public String refresh(InsData insData){
		String result = insDataService.refreshTable(insData);
		return result;
		
	}
}